<template>
  <div>
    <app-header />
    <div class="container page-container">
      <div class="dashboard-header">
        <h1>控制台</h1>
        <el-button type="primary" @click="$router.push('/create-post')">
          <el-icon><plus /></el-icon> 创建文章
        </el-button>
      </div>
      
      <el-card class="post-list-card">
        <template #header>
          <div class="card-header">
            <span>文章列表</span>
            <el-input
              v-model="search"
              placeholder="搜索文章"
              class="search-input"
              clearable
              @clear="filterPosts"
              @input="filterPosts"
            >
              <template #prefix>
                <el-icon><search /></el-icon>
              </template>
            </el-input>
          </div>
        </template>
        
        <div v-if="loading" class="loading-container">
          <el-skeleton :rows="5" animated />
        </div>
        
        <el-table 
          v-else
          :data="filteredPosts" 
          style="width: 100%"
          :empty-text="'暂无文章'"
        >
          <el-table-column prop="title" label="标题" min-width="200">
            <template #default="{ row }">
              <router-link :to="`/blog/${row.id}`" class="post-title-link">
                {{ row.title }}
              </router-link>
            </template>
          </el-table-column>
          
          <el-table-column prop="category" label="分类" width="120" />
          
          <el-table-column prop="createdAt" label="创建日期" width="180">
            <template #default="{ row }">
              {{ formatDate(row.createdAt) }}
            </template>
          </el-table-column>
          
          <el-table-column label="操作" width="180">
            <template #default="{ row }">
              <el-button-group>
                <el-button 
                  type="primary" 
                  size="small"
                  plain
                  @click="$router.push(`/edit-post/${row.id}`)"
                >
                  编辑
                </el-button>
                <el-button 
                  type="danger" 
                  size="small"
                  plain
                  @click="confirmDelete(row)"
                >
                  删除
                </el-button>
              </el-button-group>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { Plus, Search } from '@element-plus/icons-vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import axios from 'axios'
import AppHeader from '../components/app-header.vue'

const posts = ref([])
const loading = ref(true)
const search = ref('')

const fetchPosts = async () => {
  loading.value = true
  try {
    const response = await axios.get('/api/posts/all')
    posts.value = response.data
  } catch (error) {
    console.error('Failed to fetch posts:', error)
    ElMessage.error('获取文章列表失败')
  } finally {
    loading.value = false
  }
}

const filteredPosts = computed(() => {
  if (!search.value) return posts.value
  
  const searchLower = search.value.toLowerCase()
  return posts.value.filter(post => 
    post.title.toLowerCase().includes(searchLower) || 
    post.summary.toLowerCase().includes(searchLower)
  )
})

const filterPosts = () => {
  // This function is triggered by @input and @clear
  // The filtering is handled by the computed property
}

const formatDate = (dateString) => {
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN')
}

const confirmDelete = (post) => {
  ElMessageBox.confirm(
    `确定要删除文章 "${post.title}" 吗？此操作不可恢复。`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      try {
        await axios.delete(`/api/posts/${post.id}`)
        ElMessage.success('文章删除成功')
        fetchPosts()
      } catch (error) {
        console.error('Failed to delete post:', error)
        ElMessage.error('删除文章失败')
      }
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}

onMounted(() => {
  fetchPosts()
})
</script>

<style lang="less" scoped>
.dashboard-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  
  h1 {
    margin: 0;
    font-size: 28px;
    color: #303133;
  }
}

.post-list-card {
  margin-bottom: 30px;
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .search-input {
    max-width: 300px;
  }
}

.loading-container {
  padding: 20px 0;
}

.post-title-link {
  color: #409eff;
  text-decoration: none;
  
  &:hover {
    text-decoration: underline;
  }
}
</style>

